import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author LKQ
 * @date 2022/2/20 13:32
 * @description 单调栈
 */
public class FormalSolution2 {
    public static void main(String[] args) {
        FormalSolution2 formalSolution2 = new FormalSolution2();
        formalSolution2.dailyTemperatures(new int[]{73,74,75,71,69,72,76,73});
    }
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] ans = new int[n];
        // 维护一个单调栈，栈底到栈顶元素，温度逐渐递减
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            int temperature = temperatures[i];
            while (!stack.isEmpty() && temperature > temperatures[stack.peek()]) {
                int preIndex = stack.pop();
                ans[preIndex]  = i - preIndex;
            }
            stack.push(i);
        }
        return ans;
    }
}
